<template>
  <div class="login_container">
    <van-nav-bar
      class="page-nav-bar"
      title="登录"
      left-arrow
      @click-left="$router.push('/my')"
    />

    <!-- 登录表单 -->
    <van-form @submit="onSubmit" ref="loginRef">
      <van-field
        v-model="loginUerInfo.mobile"
        name="mobile"
        type="number"
        label="手机号码 "
        placeholder="手机号码 "
        :rules="userRules.mobile"
        clearable
      >
        <template #left-icon>
          <i class="iconfont icon-shouji"></i>
        </template>
      </van-field>

      <van-field
        class="codeField"
        v-model.number="loginUerInfo.code"
        type="number"
        name="code"
        label="验证码"
        placeholder="验证码"
        :rules="userRules.code"
        clearable
      >
        <template #left-icon>
          <i class="iconfont icon-yanzhengma"></i>
        </template>
        <template #button>
          <van-button
            class="send-sms-btn"
            size="small"
            type="primary"
            v-if="!isShowCountDown"
            native-type="button"
            @click="sendFn"
            >发送验证码</van-button
          >

          <van-count-down
            v-else
            :time="countTime"
            @finish="isShowCountDown = false"
          />
        </template>
      </van-field>
      <div style="margin: 16px;" class="login-btn-wrap">
        <van-button
          class="login-btn "
          round
          block
          type="info"
          native-type="submit"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { setCodeAPI, LoginAPI } from '@/api'
export default {
  name: 'LoginIndex',
  props: {},
  components: {},
  created () {},
  mounted () {},
  computed: {},
  watch: {},
  data () {
    return {
      loginUerInfo: {
        mobile: 16625197749,
        code: '246810'
      },
      userRules: {
        mobile: [
          {
            required: true,
            message: '请输入手机号'
          },
          {
            pattern: /^1[3|5|6|7|8]\d{9}$/,
            message: '手机号格式不正确',
            trigger: 'onChange'
          }
        ],
        code: [
          {
            required: true,
            message: '请输入验证码'
          },
          {
            pattern: /^\d{6}$/,
            message: '验证码格式不正确',
            trigger: 'onChange'
          }
        ]
      },
      isShowCountDown: false, // 显示倒计时按钮
      countTime: 5 * 1000 // 倒计时时间
    }
  },
  methods: {
    // 提交前会先校验，校验通过后才会进入方法
    async onSubmit (values) {
      try {
        // try 代码块中，响应报文的状态为4XX/5XX会catch,其他会正常执行
        const res = await LoginAPI(values)
        this.$toast.loading({
          message: '登陆中',
          forbidClick: true,
          duration: 1000
        })

        if (res.status === 201) {
          this.$toast.success({
            message: '登录成功',
            forbidClick: true,
            duration: 1000
          })

          this.$store.commit('setUser', res.data.data)
          this.$router.push('/my')
        } else {
          this.$toast.fail({
            message: '登录失败',
            forbidClick: true,
            duration: 1000
          })
        }
      } catch (error) {
        let errMag = '手机号或者验证码错误'
        if (error.response.status !== 400) errMag = '服务器繁忙,请稍后再试'
        this.$toast.fail({
          message: errMag,
          forbidClick: true,
          duration: 1000
        })
      }
    },
    async sendFn () {
      try {
        // 对手机号码进行校验
        await this.$refs.loginRef.validate('mobile')
      } catch (error) {
        console.dir(error)
        this.$toast.fail(error.message)
      }

      try {
        const res = await setCodeAPI(this.loginUerInfo.mobile)
        console.dir(res)
        if (res.status === 200) {
          this.$toast.success('发送成功')
          this.isShowCountDown = true
        } else {
          return this.$toast.fail('发送失败')
        }
      } catch (error) {
        // console.dir(error)
        let errMsg = '验证码发送异常'
        if (error.response.status === 404) errMsg = '手机号不正确'
        if (error.response.status === 429) {
          errMsg = '发送短信太频繁,请一分钟后再试'
        }
        return this.$toast.fail({
          message: errMsg,
          forbidClick: true,
          duration: 1000
        })
      }
    }
  }
}
</script>

<style lang="less" scoped>
.login_container {
  .iconfont {
    font-size: 37px;
  }

  .login-btn-wrap {
    padding: 53px 33px;
    .login-btn {
      background-color: #6db4fb;
      border: none;
    }
  }

  .codeField .van-field__button {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .send-sms-btn {
      width: 156px;
      height: 46px;
      line-height: 46px;
      background-color: #ededed;
      font-size: 12px;
      color: #666;
    }
    .van-count-down {
      display: inline-block;
      color: #666;
      height: 46px;
      line-height: 46px;
      font-size: 12px;
      background-color: #ededed;
      border: 1px solid gray;
    }
  }
}
</style>
